<template>
	<view>
		<view v-if="colling" class="codeCla" @click="getCode()">
			获取验证码
		</view>
		<view v-else class="codeCla">
			{{ timeData }}s后获取
		</view>
	</view>
</template>

<script>
	/**
	 *使用方法 : <verifycode :getCodeQuery="formData"></verifycode>
	 * formData对象 必须要两个值 { phoneNum:'手机号' ,codeType:'类型' }
	 * codeType（验证码类型）例如 :0=注册 1=登录 2=修改密码 3=通知 4=下单验证 5=忘记密码
	 * 可根据自身实际业务情况来定义验证码类型
	 */
	export default {
		name:"verifyCode",
		props:{
			getCodeQuery:{
				type: Object,
				default () {
					return {};
				}
			}
		},
		data() {
			return {
				timeData:59,
				colling:true,
				setIntervalSal:'',
				currentTime:'',
				coolsTime:''
			};
		},
		mounted() {
			this.isCools()
		},
		methods:{
			isCools(){
				// 判断当前倒计时是否已经过了冷却时间
				this.currentTime = new Date().getTime()  // 获取当前时间戳
				this.coolsTime = uni.getStorageSync('coolsTime')  //获取缓存中过期时间的时间戳
				if(this.coolsTime){
					// 判断冷却是否已经过了60s,<0 过期,可以再次获取验证码
					let isExpire =((new Date(this.coolsTime).getTime()  - new Date(this.currentTime).getTime())/1000).toFixed(0)
					if(isExpire<0){
						this.colling = true
						this.timeData = 59
					}else{
					// 正在冷却中,清除原有倒计时,再调用显示倒计时读秒
						this.timeData = isExpire
						this.colling = false
						this.countdown()
					}
				}else{
					this.colling = true
					this.timeData = 59
				}
			},
			getCode(){
				let  msg =  this.phoneChange(this.getCodeQuery.phoneNum)
				if(msg !== 1){
					uni.showToast({
						title: msg,
						icon: 'none',
						duration: 1500,
						mask: true
					});
					return
				}
				console.log(this.getCodeQuery)
				// 点击时获取当前时间加上60s就是过期的时间戳,存入缓存
				let expireTime = new Date().getTime() + 60000
				uni.setStorageSync('coolsTime', expireTime);
				this.countdown()
				uni.showToast({
				  title: '验证码已发送',
				  icon: 'success',
				  duration: 2000
				})
				
				// this.$api('getVerifyCode', {codeType:this.getCodeQuery.codeType,mobile:this.getCodeQuery.phoneNum} ).then(res=>{
				//  	if(res.code == 200){
				// 		// 获取客户端 短信验证码
				// 		uni.showToast({
				// 		  title: '验证码已发送',
				// 		  icon: 'success',
				// 		  duration: 2000
				// 		})
				// 	}
				//  })
			},
			countdown(){
				// 生成倒计时
				this.colling = false
				this.setIntervalSal = setInterval(() => {
					this.timeData = this.timeData - 1;
					if (this.timeData <= 0) {
						this.colling = true
						this.timeData  = 59
						clearInterval(this.setIntervalSal)
						return
					}
				}, 1000)
			},
			phoneChange(phoneNum){
				var reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;    //11位手机号码正则
				if(!phoneNum){
					return '请输入手机号'
				}
				if (!reg_tel.test(phoneNum)) {
					return '请输入正确的手机号'
				}
				return 1
			}
		}
	}
</script>

<style lang="scss" scoped>
	.codeCla{
		color: #DCC09F;
	}
</style>